package cn.nfwx.tv.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.nfwx.tv.R;

public class ItemEditView extends LinearLayout {
    private int iconRid;
    private String text;
    private ImageView iv_login;
    private EditText et_login;

    public ItemEditView(Context context) {
        this(context, null);
    }

    public ItemEditView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressLint("Recycle")
    public ItemEditView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater.from(context).inflate(R.layout.view_item_login_edit, this, true);

        ButterKnife.bind(this);

        TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.ItemEditView);
        if (t.hasValue(R.styleable.ItemEditView_loginicon)) {
            iconRid = t.getResourceId(R.styleable.ItemEditView_loginicon, 0);
        }

        if (t.hasValue(R.styleable.ItemEditView_loginhint)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (t.getType(R.styleable.ItemEditView_loginhint) == TypedValue.TYPE_STRING) {
                    text = t.getString(R.styleable.ItemEditView_loginhint);
                } else if (t.getType(R.styleable.ItemEditView_loginhint) == TypedValue.TYPE_REFERENCE) {
                    int rid = t.getResourceId(R.styleable.ItemEditView_loginhint, -1);
                    if (rid != -1) {
                        text = context.getString(rid);
                    }
                }
            } else {
                text = t.getString(R.styleable.ItemEditView_loginhint);
                int rid = t.getResourceId(R.styleable.ItemEditView_loginhint, -1);
                if (rid != -1) {
                    text = context.getString(rid);
                }
            }
        }

        t.recycle();

        init();
    }

    private void init() {
        iv_login = findViewById(R.id.iv_login);
        et_login = findViewById(R.id.et_login);

        iv_login.setImageResource(iconRid);
        et_login.setHint(text);
    }

    public void setFilters(InputFilter[] filters) {
        et_login.setFilters(filters);
    }

    public Editable getText() {
        return et_login.getText();
    }

    public void setText(String str) {
        et_login.setText(str);
    }
}
